from django.template import Library, Node, Variable, resolve_variable
from django.db.models import get_model

register = Library()

def get_model_magictags(parser, token):
    bits = token.contents.split()
    model = bits[1]
    varname = bits[3]
    return ModelMagictagsNode(model, varname)

class ModelMagictagsNode(Node):
    def __init__(self, model, varname):
        self.model = model
        self.varname = varname

    def render(self, context):
        Tag = get_model('magictags', 'Tag')
        #get all Tags that are applied to any of the model
        field_name = str(self.model)
        tags = Tag.objects.filter(**{field_name + '__gt': 0}).distinct()
        context[self.varname] = tags
        return ''
get_model_magictags = register.tag(get_model_magictags)


#Get all Tags that are applied to any given list of objects
@register.inclusion_tag('magictags/filterby.html')
def get_list_magictags(list, control_group_name):
    #get all the Tags that are applied to objects in the list passed in
    Tag = get_model('magictags', 'Tag')
    tags = []
    for item in list:
        for tag in item.tags.all():
            if tag not in tags:
                tags.append(tag)
    #if no tags, don't display
    display = False
    tag_count = len(tags)
    if tag_count > 0:
        display = True
    
    if display == True:
        return {'tags': tags, 'control_group_name': control_group_name}


#Tag an item with its appropriate magictags
def magictag(item):
    css_classes = 'mtagged'
    for tag in item.tags.all():
        css_classes += ' mtag-' + str(tag.slug)
    return css_classes

register.simple_tag(magictag)

